import { Button, DatePicker, Form, Input, Select } from "antd";
import { isNil, isEmpty, pickBy } from "lodash";
import * as React from "react";
import styles from "./style.module.less";
const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;

interface Schema {
  label: string;
  type: string;
  value?: string;
  options?: any;
  componentOptions?: object;
  style?: object;
  defaultValue?: any;
}
interface Props {
  conditions: Schema[];
  form: any;
  onSubmit: any;
}
class ConditionSelector extends React.Component<Props, any> {
  public handleReset = () => {
    this.props.form.resetFields();
    this.handleSubmit();
  };
  public handleSubmit = (e?) => {
    e && e.preventDefault();
    this.props.form.validateFields((err, values) => {
      const takeNecessary = (value: any): boolean =>
        !isNil(value) && !isEmpty(value);
      const condition = pickBy(takeNecessary, values);
      this.props.onSubmit(condition);
    });
  };
  public componentSelector = component => {
    if (isEmpty(component.type)) {
      return null;
    }
    const { componentOptions: config, style = {} } = component;
    switch (component.type.toLowerCase()) {
      case "date":
        return <DatePicker {...config} style={style} />;
      case "range":
        return <RangePicker {...config} style={{width: 260, ...style}} />;
      case "select":
        return (
          <Select style={{ width: 160, ...style }} {...config}>
            {component.options.map((o, index) => {
              return (
                <Option key={index} value={o.key}>
                  {o.label}
                </Option>
              );
            })}
          </Select>
        );
      default:
        return <Input {...config} style={style} />;
    }
  };
  public render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <section className={styles["search-bar"]}>
        <Form layout="inline">
          {this.props.conditions.map((d, index) => {
            return (
              <FormItem key={index} label={d.label}>
                {getFieldDecorator(d.value, {
                  initialValue: d.defaultValue
                })(this.componentSelector(d))}
              </FormItem>
            );
          })}

          <FormItem style={{ float: "right", marginRight: 0 }}>
            <Button type="primary" onClick={this.handleSubmit}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
              重置
            </Button>
          </FormItem>
        </Form>
      </section>
    );
  }
}

const ConditionSelectorFrom = Form.create()(ConditionSelector);
export default ConditionSelectorFrom;
